package com.sendpo.zjx.sendpo.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchandiseDomain;
import com.sendpo.zjx.sendpo.domain.UserAddressDomain;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.table.UserAddress;
import com.sendpo.zjx.sendpo.utils.MD5Util;
import com.sendpo.zjx.sendpo.utils.OrderInfoUtil2_0;
import com.sendpo.zjx.sendpo.utils.PayDomain;
import com.sendpo.zjx.sendpo.utils.PayResult;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/18.
 */

public class BuyGenericStoreActivity extends AppCompatActivity {

    @BindView(R.id.left_add)
    TextView leftAdd;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.realname)
    TextView realname;
    @BindView(R.id.head_iv)
    ImageView headIv;
    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.nowprice_tv)
    TextView nowpriceTv;
    @BindView(R.id.origin_tv)
    TextView originTv;
    private Dialog paydialog;
    private RadioGroup radioGroup;
    public MerchandiseDomain.DataBean dataBean=null;
    public UserAddress userAddress=null;
    public static  final int SELECTED_ADDRESS=1001;
    @BindView(value = R.id.iphone)
    public TextView iphone;
    @BindView(value = R.id.address)
    public TextView address;
    @BindView(value = R.id.number_edit)
    public EditText number_edit;
    private double baoyou=0.00;
    @BindView(value = R.id.finalmoney)
    public TextView finalmoney;
    @BindView(value = R.id.typespinner)
    public Spinner typespinner;
    public int spiner_position=0;
    public Dialog loadingdialog = null;
    @BindView(value = R.id.content_edit)
    public EditText content_edit;
    private String orderId="";
    private String paymoney="";
    @BindView(value = R.id.left_addresmmap)
    public RelativeLayout left_addresmmap;
    @BindView(value = R.id.addaddress_tv)
    public TextView addaddress_tv;
    public Dialog confirm_dialog=null;
    @BindView(value = R.id.peisongfree_tv)
    public TextView peisongfree_tv;
    public int type=0;
    private  String final_money="0.00";
    @BindView(value = R.id.jifenpinner)
    public Spinner jifenpinner;
     @BindView(value = R.id.jifenfree_tv)
     public TextView jifenfree_tv;
    public int jifentype=0;
    @BindView(value = R.id.jifen_rl1)
    public RelativeLayout jifen_rl1;
    @BindView(value = R.id.jifen_rl2)
    public RelativeLayout jifen_rl2;
    public int num=0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buygenericstore);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
        initPayDialog();
    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpUrl.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Gson gson=new Gson();
                        PayDomain pay=gson.fromJson(payResult.getResult(),PayDomain.class);
//                          paysuccess(orderId);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        System.out.println("***************"+payResult.getResult());
                      Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                    finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        };
    };

    public void payV2(String total_account,String title,String content) {
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(HttpUrl.PAY_APPID,total_account,title,content, false);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String privateKey = HttpUrl.PAY_RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, false);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(BuyGenericStoreActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = HttpUrl.SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void initComponent() {
         query();
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dataBean= (MerchandiseDomain.DataBean) getIntent().getSerializableExtra("data");
        baoyou=Double.parseDouble(dataBean.getMerchandisePeisongfee());
        type=getIntent().getIntExtra("type",0);
        if(dataBean!=null){
            if(dataBean.getMerchandiseAllowjifen()==0){
                jifen_rl1.setVisibility(View.GONE);
                jifen_rl2.setVisibility(View.GONE);
            }
            jifenfree_tv.setText("使用积分方式支付："+dataBean.getMerchandiseKouchujifen()+"积分+"+"¥"+dataBean.getMerchandiseJifenmoney());
            Glide.with(this)
                    .load(dataBean.getMerchandiseHeadimg())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .into(headIv);
            title.setText(dataBean.getMerchandiseName()+"");
            originTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
            originTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线
            originTv.getPaint().setAntiAlias(true);// 抗锯齿
            originTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰
            if(dataBean.getMerchandiseOriginalprice().equals(dataBean.getMerchandiseCurrentprice())){
                originTv.setVisibility(View.GONE);
            }else{
                originTv.setVisibility(View.VISIBLE);
            }
            peisongfree_tv.setText("配送费用：¥"+dataBean.getMerchandisePeisongfee());
            nowpriceTv.setText("¥"+dataBean.getMerchandiseCurrentprice()+"");
            originTv.setText("¥"+dataBean.getMerchandiseOriginalprice()+"");
            number_edit.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if(TextUtils.isEmpty(number_edit.getText().toString().trim())){
                        return;
                    }
                    if(Tools.isInteger(number_edit.getText().toString().trim())){
                        int num=Integer.parseInt(number_edit.getText().toString().trim());
                        if(num!=0){
                            String price="0.00";
                            if(jifentype==0){
                                price=dataBean.getMerchandiseCurrentprice();
                            }else{
                                price=dataBean.getMerchandiseJifenmoney();
                            }
                            double  nummoney=num*Double.parseDouble(price);
                            double  finalmo=0.00;
                            if(spiner_position==0){
                                finalmo=nummoney+baoyou;
                            }else if(spiner_position==1){
                                finalmo=nummoney;
                            }
                            DecimalFormat format=new DecimalFormat("0.00");
                            final_money=format.format(finalmo)+"";
                            if(jifentype==0){
                                finalmoney.setText("¥"+final_money);
                            }else{
                                finalmoney.setText(num*Integer.parseInt(dataBean.getMerchandiseKouchujifen())+"积分"+"¥"+final_money);
                            }
                        }else{
                            final_money="0.00";
                            finalmoney.setText("¥0.00");
                        }

                    }

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                                              int after) {
                    // 输入前的监听

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // 输入后的监听


                }
            });
            jifenpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    jifentype=i;
                    if(Tools.isInteger(number_edit.getText().toString().trim())){
                        int num=Integer.parseInt(number_edit.getText().toString().trim());
                        if(num!=0){
                            String price="0.00";
                            if(jifentype==0){
                                price=dataBean.getMerchandiseCurrentprice();
                            }else{
                                price=dataBean.getMerchandiseJifenmoney();
                            }
                            double  nummoney=num*Double.parseDouble(price);
                            double  finalmo=0.00;
                            if(spiner_position==0){
                                finalmo=nummoney+baoyou;
                            }else if(spiner_position==1){
                                finalmo=nummoney;
                            }
                            DecimalFormat format=new DecimalFormat("0.00");
                            final_money=format.format(finalmo)+"";
                            finalmoney.setText("¥"+final_money);
//                            if(jifentype==0){
//                                finalmoney.setText("¥"+final_money);
//                            }else{
//                                finalmoney.setText(num*Integer.parseInt(dataBean.getMerchandiseKouchujifen())+"积分"+"¥"+final_money);
//                            }
                        }else{
                            final_money="0.00";
                            finalmoney.setText("¥"+"0.00");
                        }

                    }
                }


                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });

            String price="0.00";
         if(jifentype==0){
            price=dataBean.getMerchandiseCurrentprice();
            }else{
               price=dataBean.getMerchandiseJifenmoney();
             }
            price=dataBean.getMerchandiseCurrentprice();
            double xianzai=Double.parseDouble(price);
            DecimalFormat decimalFormat=new DecimalFormat("0.00");
            final_money=decimalFormat.format((xianzai+baoyou))+"";
            finalmoney.setText(""+price);
//            if(jifentype==0){
//                finalmoney.setText("¥"+final_money);
//            }else{
//                finalmoney.setText(dataBean.getMerchandiseKouchujifen()+"积分"+"¥"+final_money);
//            }

        }
        typespinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        spiner_position = 0;
                        break;
                    case 1:
                        spiner_position = 1;
                        break;
                }
                if(Tools.isInteger(number_edit.getText().toString().trim())){
                    int num=Integer.parseInt(number_edit.getText().toString().trim());
                    if(num!=0){
                        String price="0.00";
                        if(jifentype==0){
                            price=dataBean.getMerchandiseCurrentprice();
                        }else{
                            price=dataBean.getMerchandiseJifenmoney();
                        }
                        double  nummoney=num*Double.parseDouble(price);
                        double  finalmo=0.00;
                        if(spiner_position==0){
                            finalmo=nummoney+baoyou;
                        }else if(spiner_position==1){
                            finalmo=nummoney;
                        }
                        DecimalFormat format=new DecimalFormat("0.00");
                        final_money=format.format(finalmo)+"";
                        if(jifentype==0){
                            finalmoney.setText("¥"+final_money);
                        }else{
                            finalmoney.setText(num*Integer.parseInt(dataBean.getMerchandiseKouchujifen())+"积分"+"¥"+final_money);
                        }
                    }else{
                        final_money="0.00";
                        finalmoney.setText("¥"+"0.00");
                    }

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
    @OnClick(value = {R.id.backbt, R.id.selectaddress_bt, R.id.submit_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.selectaddress_bt:
                Intent selectaddress= new Intent(this,AddressListActivity.class);
                startActivityForResult(selectaddress,SELECTED_ADDRESS);
                break;
            case R.id.submit_bt:
                System.out.println("***************888");
                final List<User> userList = Xutils.queryAll(getApplication(), User.class);
          if (userList == null || userList.size() == 0) {
     Tools.redirectActivity(BuyGenericStoreActivity.this,LoginActivity.class);
            return;
          }
                if(!TextUtils.isEmpty(orderId)){
                    Toast.makeText(getApplicationContext(),"已经生成订单，请支付",Toast.LENGTH_SHORT).show();
                    paydialog.show();
                    return;
                }
                if(userAddress==null){
                    Toast.makeText(getApplicationContext(),"请选择地址信息",Toast.LENGTH_SHORT).show();
                    Intent address= new Intent(this,AddressListActivity.class);
                    startActivityForResult(address,SELECTED_ADDRESS);
                    return;
                }
                if(TextUtils.isEmpty(number_edit.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"数量不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(Tools.isInteger(number_edit.getText().toString().trim())){
                    if(Integer.parseInt(number_edit.getText().toString().trim())==0){
                        Toast.makeText(getApplicationContext(),"数量不能为0",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String orderDeliveryMoney="";

                    if(spiner_position==0){
                        orderDeliveryMoney=baoyou+"";
                    }else{
                        orderDeliveryMoney="";
                    }
                    num= Integer.parseInt(number_edit.getText().toString().trim());
                    JSONObject  jsonObject=new JSONObject();
                    try {
                        DecimalFormat decimalFormat=new DecimalFormat("0.00");
                        jsonObject.put("userId",""+userList.get(0).getUserId());
                        jsonObject.put("remarks",""+content_edit.getText().toString().trim());
                        jsonObject.put("deliveryType",""+spiner_position);
                        jsonObject.put("userAddressId",""+userAddress.getAddressId());
                        jsonObject.put("price",""+decimalFormat.format(Double.parseDouble(final_money)));
                        double origin=0.0;
                         if(spiner_position==0){
                           origin=num*Double.parseDouble(dataBean.getMerchandiseOriginalprice())+baoyou;
                         }else{
                           origin=num*Double.parseDouble(dataBean.getMerchandiseOriginalprice());
                         }
                        jsonObject.put("originalPrice",""+decimalFormat.format(origin));
                        JSONArray jsonArray=new JSONArray();
                        JSONObject rea=new JSONObject();
                        rea.put("productId",""+dataBean.getMerchandiseId());
                        rea.put("price",dataBean.getMerchandiseCurrentprice());
                        if(dataBean.getMerchantsId()==1){
                            rea.put("type","2");
                        }else{
                            rea.put("type","1");
                        }
                        rea.put("count",""+num);
                        jsonArray.put(rea);
                        jsonObject.put("relations",jsonArray);
                        createorder(jsonObject);
                        System.out.println("*********************jsonObject:"+jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else{
                    Toast.makeText(getApplicationContext(),"数量不能为空",Toast.LENGTH_SHORT).show();
                }

                break;

        }
    }
    public void  initPayDialog(){
        confirm_dialog=new Dialog(this);
        confirm_dialog.setContentView(R.layout.dialog_paymoney);
        confirm_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        final EditText confirm_edit_tv=confirm_dialog.findViewById(R.id.edit_tv);
        TextView exitbt=confirm_dialog.findViewById(R.id.exitbt);
        exitbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirm_dialog.dismiss();
            }
        });
        TextView readby=confirm_dialog.findViewById(R.id.readby);
        readby.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("***********************readby");
                if(TextUtils.isEmpty(confirm_edit_tv.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"支付密码不能为空",Toast.LENGTH_LONG).show();
                    return;
                }
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    return;
                }
                User user=userList.get(0);
                if(TextUtils.equals(MD5Util.getMD5(confirm_edit_tv.getText().toString().trim()), user.getUserPaypassword())){
                    yuyue(orderId,user.getUserId()+"");
                }else{
                    Toast.makeText(getApplicationContext(),"输入支付密码不正确",Toast.LENGTH_LONG).show();
                }

            }
        });

        paydialog=new Dialog(this);
        paydialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        paydialog.setContentView(R.layout.dialog_rechargemoney);
        radioGroup=paydialog.findViewById(R.id.rg_pay);
        TextView recharage_title=paydialog.findViewById(R.id.recharage_title);
        recharage_title.setText("结算支付");
        EditText recharge_edit= paydialog.findViewById(R.id.recharge_edit);
        recharge_edit.setVisibility(View.GONE);
        View yuyue_left=paydialog.findViewById(R.id.yuyue_left);
        yuyue_left.setVisibility(View.VISIBLE);
        final RadioButton pay_moneypackage=paydialog.findViewById(R.id.pay_moneypackage);
        pay_moneypackage.setVisibility(View.VISIBLE);
        pay_moneypackage.setChecked(true);
        final RadioButton pay_wexin=paydialog.findViewById(R.id.pay_wexin);
        pay_wexin.setChecked(false);
        paydialog.findViewById(R.id.moneycount_rl);

        Button paybt=paydialog.findViewById(R.id.paybt);

        paybt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    return;
                }
                User user=userList.get(0);
                switch (radioGroup.getCheckedRadioButtonId()){
                    case R.id.pay_moneypackage:
//                        if(jifentype==1){
//                           int number=Integer.parseInt(dataBean.getMerchandiseKouchujifen())*num;
//                             if(Integer.parseInt(user.getUserJifen())-number<0){
//                Toast.makeText(getApplicationContext(),"积分不足！无法购买",Toast.LENGTH_SHORT).show();
//                                 return;
//                             }
//                        }
                        if(TextUtils.isEmpty(user.getUserPaypassword())){
                            Intent paypass=new Intent(BuyGenericStoreActivity.this,ModifyPayPassActivity.class);
                            startActivity(paypass);
                            return;
                        }
                        paydialog.dismiss();
                        confirm_edit_tv.getText().clear();
                        confirm_dialog.show();
                        break;
                    case R.id.pay_wexin:
                        Toast.makeText(getApplicationContext(),"微信支付"
                                ,Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.pay_paypackage:
                        zhifubao(orderId,user.getUserId()+"");
                   //paymoney
//                        if(jifentype==1){
//                            int number=Integer.parseInt(dataBean.getMerchandiseKouchujifen())*num;
//                            if(Integer.parseInt(user.getUserJifen())-number<0){
//                                Toast.makeText(getApplicationContext(),"积分不足！无法购买",Toast.LENGTH_SHORT).show();
//                                return;
//                            }
//                        }

                        break;
                }
            }
        });
        yuyue_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_moneypackage.setChecked(true);
            }
        });
        RelativeLayout wx_rl=paydialog.findViewById(R.id.wx_rl);
        wx_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_wexin.setChecked(true);
            }
        });
        final RadioButton pay_paypackage=paydialog.findViewById(R.id.pay_paypackage);
        RelativeLayout pay_rl=paydialog.findViewById(R.id.pay_rl);
        pay_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_paypackage.setChecked(true);
            }
        });


    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK){
            return;
        }
        switch (requestCode){
            case SELECTED_ADDRESS:
                if(data!=null){
                    userAddress= (UserAddress) data.getSerializableExtra("address_data");
                    realname.setText(userAddress.getUserConsignee());
                    iphone.setText(""+userAddress.getUserIphone());
                    address.setText(userAddress.getUserCity()+userAddress.getUserDetailedAddress());
                    left_addresmmap.setVisibility(View.VISIBLE);
                    addaddress_tv.setText("");
                }
                break;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        webUserServer();
    }

    public void createOrder(String userId,
                            String merchantsId,
                            String merchandiseId,
                            String orderMoney,
                            String orderNnumber,
                            String orderDeliveryMethod,
                            String orderDeliveryMoney,
                            String orderBuyerMessage,
                            String orderType,
                            String orderAllowjifen
   ){
       loadingdialog.show();
       Map<String,String> map=new HashMap<>();
        map.put("userId",userId+"");
        map.put("merchantsId",""+merchantsId);
       map.put("merchandiseId",""+merchandiseId);
       map.put("orderState","0");
       map.put("orderMoney",""+orderMoney);
       map.put("orderNumber",""+orderNnumber);
       map.put("orderDeliveryMethod",""+orderDeliveryMethod);
       map.put("orderDeliveryMoney",""+orderDeliveryMoney);
       map.put("orderBuyerMessage",""+orderBuyerMessage);
       map.put("userCity",""+userAddress.getUserCity());
       map.put("userConsignee",""+userAddress.getUserConsignee());
       map.put("userDetailedAddress",""+userAddress.getUserDetailedAddress());
       map.put("userIphone",""+userAddress.getUserIphone());
       map.put("orderType",""+orderType);
       map.put("orderAllowjifen",orderAllowjifen);
       Xutils.POST(HttpUrl.ordermerchandisecreateorder, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                JSONObject jb= null;
                try {
                    jb = new JSONObject(result);
                    Toast.makeText(getApplicationContext(),""+jb.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (jb.getInt("state")){
                        case HttpCode.SUCCESS:
                            JSONObject data=jb.getJSONObject("data");
                            orderId= data.getString("orderId");
                            paymoney=data.getString("orderMoney");
                            paydialog.show();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),""+"创建订单失败",Toast.LENGTH_SHORT).show();
                loadingdialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
     });;


   }

    public void reduceMoney(String orderMoney,String orderId){
        paydialog.dismiss();
        Map<String,String> map=new HashMap<>();
        List<User> users= Xutils.queryAll(getApplication(),User.class);
        if(users==null||users.size()==0){
            return;
        }
        User user=users.get(0);
        map.put("userId",""+user.getUserId()+"");
        map.put("orderMoney",orderMoney+"");
        map.put("orderId",orderId+"");
        Xutils.POST(HttpUrl.ordermerchandisereducebyusermoney, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                webUserServer();
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")){
                        case  HttpCode.SUCCESS:
                            finish();
                            break;
                        case HttpCode.PAY_NUM_NO:

                            break;
                        case HttpCode.ERROR:
                            Map<String,Object> map1=new HashMap<>();
                            confirm_dialog.dismiss();
                           Tools.redirectActivity(BuyGenericStoreActivity.this,UserMoneyCenterActivity.class,map1);
                            break;
                        case HttpCode.THROW:
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
//
    public void paysuccess(String orderId){
        Map<String,String> map=new HashMap<>();
        map.put("orderId",orderId+"");
        Xutils.POST(HttpUrl.ordermerchandiseupdatebydisanfang, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                webUserServer();
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")){
                        case  HttpCode.SUCCESS:

                            paydialog.dismiss();
                            finish();

                            break;
                        case HttpCode.ERROR:
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void query(){
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User user = userList.get(0);
        Map<String,String> map=new HashMap<>();
        map.put("userId",user.getUserId()+"");
        Xutils.POST(HttpUrl.useraddressbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                UserAddressDomain domain= gson.fromJson(result, UserAddressDomain.class);
                switch (domain.state){
                    case HttpCode.SUCCESS:
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                            userAddress= domain.getData().get(0);
                            realname.setText(userAddress.getUserConsignee());
                            iphone.setText(""+userAddress.getUserIphone());
                            address.setText(userAddress.getUserCity()+userAddress.getUserDetailedAddress());
                            left_addresmmap.setVisibility(View.VISIBLE);
                            addaddress_tv.setText("");
                        }
                        break;

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    public void webUserServer() {
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId", userList.get(0).getUserId() + "");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserDomain userDomain = gson.fromJson(result, UserDomain.class);
                switch (userDomain.getState()) {
                    case HttpCode.SUCCESS:
                        User user = userDomain.getData();
                        user.setId(userList.get(0).getId());
                        Xutils.update(getApplication(), user);
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    //y有条件
    public void  createorder(final JSONObject jsonObject){
        loadingdialog.show();
        RequestParams requestParams=new RequestParams(HttpUrl.generateOrder);
        requestParams.setAsJsonContent(true);
        requestParams.setBodyContent(jsonObject.toString());
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                System.out.println("********************"+result);
                try {
                    JSONObject jsonObject1=new JSONObject(result);

                    if(jsonObject1.getBoolean("flag")){
                        Toast.makeText(getApplicationContext(),"生成订单成功",Toast.LENGTH_SHORT).show();
                        orderId= jsonObject1.getInt("data")+"";
                        paymoney=jsonObject.getString("price");
                        paydialog.show();
                    }else{
                        Toast.makeText(getApplicationContext(),"生成订单失败",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //余额支付
    public void  yuyue(String orderId,String userId){
           Map<String,String>  map=new HashMap<>();
           map.put("id",""+orderId);
             map.put("userId",""+userId);
        Xutils.GET(HttpUrl.orderUserMoneyPay, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject json=new JSONObject(result);

                if(json.getBoolean("flag")){
                    Toast.makeText(getApplicationContext(),"购买成功",Toast.LENGTH_SHORT).show();
                    finish();
                   }else{
                    Toast.makeText(getApplicationContext(),"余额不足，购买失败",Toast.LENGTH_SHORT).show();
                }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //支付宝支付
    public void  zhifubao(String orderId,String userId){
        Map<String,String>  map=new HashMap<>();
        map.put("id",""+orderId);
        map.put("userId",""+userId);
        Xutils.GET(HttpUrl.orderAliPay, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    final JSONObject json=new JSONObject(result);
                    if(json.getBoolean("flag")){
                        Toast.makeText(getApplicationContext(),"打开支付宝",Toast.LENGTH_SHORT).show();
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(BuyGenericStoreActivity.this);
                                Map<String, String> result = null;
                                try {
                                    result = alipay.payV2(json.getString("data"), true);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                Message msg = new Message();
                                msg.what = HttpUrl.SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }else{
                        Toast.makeText(getApplicationContext(),json.getString("msg"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
